import 'dart:typed_data';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:share_extend/share_extend.dart';
import 'package:thinking/config/_.dart';
import 'package:thinking/service/DynamicService.dart';
import 'package:thinking/service/PublicService.dart';
import 'package:thinking/widget/_.dart';
import 'package:thinking/utils/_.dart';
import 'package:thinking/entity/_.dart';
import 'dart:math' as math;

class DynamicItem extends StatefulWidget {
  final DynamicDataEntity dynamicData;

  DynamicItem({required Key key, required this.dynamicData}) : super(key: key);

  @override
  _DynamicItem createState() => _DynamicItem(dynamicData: dynamicData);
}

class _DynamicItem extends State<DynamicItem>
    with SingleTickerProviderStateMixin {
  DynamicDataEntity dynamicData;

  _DynamicItem({required this.dynamicData});

  late AnimationController _animationController;
  late Animation<double> _animation;

  @override
  void initState() {
    super.initState();
    _animationController =
        AnimationController(vsync: this, duration: Duration(milliseconds: 300));
    _animation = Tween(begin: 0.0, end: 1.0).animate(_animationController);
    _animationController.forward();
  }

  @override
  void dispose() {
    super.dispose();
    _animationController.dispose();
  }

  /// 保存图片到相册
  saveGallery(String url) async {
    var response = await PublicService.downImage(url: url, params: {});
    String fileName = Tool.randomBit();
    final result = await ImageGallerySaver.saveImage(
        Uint8List.fromList(response),
        quality: 100,
        name: fileName
    );
    result['isSuccess']
        ? BotToast.showText( text: '图片存储在 ${result['filePath']}')
        : BotToast.showText( text:"保存失败");
  }

  /// 分享给好友
  shareImg() async {
    ShareExtend.share(
      "[有人@你]\n有人发了条动态\n\n${dynamicData.dynamicIntroduce}\n\n动态访问地址：http://192.168.31.202:4001/app/thinking.apk",
      "text",
      sharePanelTitle: "thinking",
    );
  }

  Future<void> changeCollection()async{

    dynamicData.setDynamicIsCollection = !dynamicData.dynamicIsCollection!;

    await DynamicService.changeDynamicCollection(params: {
      'user_Id':SPreferences().getInt('user_Id'),
      'dynamic_Id':dynamicData.dynamicId,
      'isCollection':dynamicData.dynamicIsCollection
    });
    if(dynamicData.dynamicIsCollection!) BotToast.showText(text: '收藏成功');
  }


  @override
  Widget build(BuildContext context) {
    return FadeTransition(
        opacity: _animation,
        child: Panel(
          top: 10,
          bottom: 10,
          child: Column(
            children: [
              Row(
                children: [
                  GestureDetector(
                    onTap: () {
                      Modular.to.pushNamed('/personal/${dynamicData.dynamicUser!.userId}');
                    },
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(40),
                      child: ClipOval(
                        child: Image.network(
                          dynamicData.dynamicUser!.userHeadImg!,
                          width: Screen.setWidth(40),
                          height: Screen.setWidth(40),
                          fit: BoxFit.cover,
                        ),
                      ),
                    ),
                  ),
                  Expanded(
                      child: Container(
                    margin: EdgeInsets.only(left: 10),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          dynamicData.dynamicUser!.userNickName != null
                              ? dynamicData.dynamicUser!.userNickName!
                              : dynamicData.dynamicUser!.userPhone!,
                          overflow: TextOverflow.ellipsis,
                        ),
                        Text(
                          Tool.dateAndTimeToString(
                            Tool.timeToStamp(dynamicData.dynamicTime!),
                            formart: {"y-m": "-", "m-d": "-", "h-m": ":"},
                          ),
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              fontSize: 12, color: ColorConfig.TextColor),
                        ),
                      ],
                    ),
                  )),
                  GestureDetector(
                    onTap: () async {
                      await showDialog(
                          context: context,
                          builder: (context) {
                        return SimpleDialog(
                          titlePadding: EdgeInsets.all(15),
                          contentPadding: EdgeInsets.all(15),
                          title: Container(
                            alignment: Alignment.centerLeft,
                            child: Row(
                              children: [
                                Icon(Icons.touch_app,size: 30,color: ColorConfig.ThemeColor,),
                                SizedBox(width: 5,),
                                Text("请选择操作",style: TextStyle(fontSize: 17),)
                              ],
                            ),
                          ),
                          children: <Widget>[
                            TextButton(
                                child: Text("保存到相册",style: TextStyle(color: ColorConfig.ThemeColor,fontSize: 16),),
                                onPressed: () async {
                                  Navigator.of(context).pop();
                                  await saveGallery(dynamicData.dynamicImg!
                                  );
                                }
                            ),
                            TextButton(
                                child: Text("收藏",style: TextStyle(color: ColorConfig.ThemeColor,fontSize: 16),),
                                onPressed: () async {
                                  Navigator.of(context).pop();
                                  await changeCollection(
                                  );
                                }
                            ),
                            TextButton(
                                child: Text("分享",style: TextStyle(color: ColorConfig.ThemeColor,fontSize: 16),),
                                onPressed: () async {
                                  Navigator.of(context).pop();
                                  await shareImg(
                                  );
                                }
                            ),

                          ],
                        );
                      }
                      );
                    },
                    child: Transform.rotate(
                      //旋转90度
                      angle: math.pi / 2,
                      child: Icon(Icons.more_horiz),
                    ),
                  ),
                ],
              ),
              GestureDetector(
                onTap: () {
                  Modular.to.pushNamed('/dynamicInfoWidget/${dynamicData.dynamicId}');
                },
                child: Container(
                  margin: EdgeInsets.only(top: 10),
                  alignment: Alignment.centerLeft,
                  child: RichText(
                    textAlign: TextAlign.left,
                    text: TextSpan(children: <InlineSpan>[
                      TextSpan(
                          children: dynamicData.dynamicTagList != null
                              ? dynamicData.dynamicTagList!
                                  .map((e) => TextSpan(
                                      text: '#' + e + ' ',
                                      style: TextStyle(
                                          color: Colors.lightBlue,
                                          fontStyle: FontStyle.italic,
                                          fontSize: 14)))
                                  .toList()
                              : null),
                      TextSpan(
                          text: dynamicData.dynamicIntroduce,
                          style: TextStyle(
                              fontSize: 14,
                              color: Colors.black87,
                              overflow: TextOverflow.ellipsis))
                    ]),
                  ),
                ),
              ),
             dynamicData.dynamicImg!=null? GestureDetector(
               onTap: () {
                 Modular.to.pushNamed('/dynamicInfoWidget/${dynamicData.dynamicId}');
               },
               child: Container(
                 margin: EdgeInsets.only(top: 10),
                 alignment: Alignment.centerLeft,
                 child: ClipRRect(
                   borderRadius: BorderRadius.all(Radius.circular(10)),
                   child: Image.network(
                     dynamicData.dynamicImg!,
                     filterQuality: FilterQuality.low,
                     width: Screen.width(context),
                     fit: BoxFit.cover,
                   ),
                 ),
               ),
             ):Container(),
              Container(
                margin: EdgeInsets.only(top: 10),
                child: DynamicData(
                  onLike: (bool isLike) async {
                    await DynamicService.changeDynamicLike(params: {
                      'user_Id': SPreferences().getInt('user_Id'),
                      'dynamic_Id': dynamicData.dynamicId,
                      'isLike': isLike
                    });
                  },
                  onShare: () {},
                  dynamicData: dynamicData,
                ),
              )
            ],
          ),
        ));
  }
}
